﻿Imports IControl.IControls
Imports DevExpress.LookAndFeel
Imports DevExpress.XtraEditors
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraLayout
Imports System.Drawing
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraPrinting

Public Class IFormDon
    Private dtThongTin, dtDanhSach As DataTable
    Private m_TaoMoi, m_Sua, m_Xoa As Boolean
    Private iclass As IClass = New IClass
    Private ds As DataSet
    Private dt As DataTable
    Private bd As BindingSource
    Private am, ad As Object
    Protected state As Integer
    Protected controlFocus As BaseEdit
    Protected ht, htNew, htEdit As Hashtable
    Protected lstGuiIdDeleted As ArrayList
    Private Sub view_CustomDrawRowIndicator(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs) Handles view.CustomDrawRowIndicator
        Dim view As GridView = DirectCast(sender, GridView)
        Dim indicatorIcon As Boolean = False
        If e.RowHandle >= 0 Then 'trừ trường hợp -1
            'Check whether the indicator cell belongs to a data row
            If e.Info.IsRowIndicator Then
                e.Info.DisplayText = (e.RowHandle + 1).ToString()
                If Not indicatorIcon Then
                    e.Info.ImageIndex = -1
                End If
            End If
        End If
    End Sub
    ''' <summary>
    ''' Set các thông tin trên report (in trực tiếp ra từ lưới xtragrid)
    ''' </summary>
    ''' <param name="title">Tiêu đề report</param>
    ''' <param name="ten_donvisudung">Thông tin đơn vị sử dụng</param>
    ''' <param name="diachi_donvisudung">Địa chỉ đơn vị sử dụng</param>
    ''' <remarks></remarks>
    Public Sub setTitle_Header_Report(ByVal title As String, ByVal ten_donvisudung As String, ByVal diachi_donvisudung As String)
        Me.IGridView1.setTitle(title)
        'Me.IGridView1.setHeaderFooter(ten_donvisudung, diachi_donvisudung, Me.printingSystem1, Me.PrintableComponentLink1)
        PrintableComponentLink1.ClearDocument() 'thử
        PrintableComponentLink1.Landscape = True
        Dim leftColumn As String = ten_donvisudung.ToUpper & vbCrLf & ten_donvisudung.ToUpper
        Dim middleColumn As String = "[Tên Người dùng]"
        '======== footer ======================
        Dim leftColumnFooter As String = "[Trang # / #]"
        Dim rightColumnfooter As String = "[Giờ in][Ngày in]"
        ' Create a PageHeaderFooter object and initializing it with
        ' the link's PageHeaderFooter.
        Dim phf As PageHeaderFooter = TryCast(PrintableComponentLink1.PageHeaderFooter, PageHeaderFooter)
        Dim phfooter As PageHeaderFooter = TryCast(PrintableComponentLink1.PageHeaderFooter, PageHeaderFooter)
        ' Clear the PageHeaderFooter's contents.
        phf.Header.Content.Clear()

        ' Add custom information to the link's header.
        phf.Header.Content.AddRange(New String() {leftColumn, "", Nothing})
        'set title
        'AddHandler PrintableComponentLink2.CreateReportHeaderArea, AddressOf PrintableComponentLink2_CreateReportHeaderArea
        phf.Header.LineAlignment = BrickAlignment.Center

        ' Show the document's preview.
        phfooter.Footer.Content.Clear()
        phf.Footer.Content.AddRange(New String() {leftColumnFooter, middleColumn, rightColumnfooter})
        phf.Footer.LineAlignment = BrickAlignment.Center
        PrintableComponentLink1.ShowRibbonPreview(UserLookAndFeel.Default)
    End Sub
    Private WithEvents view As DevExpress.XtraGrid.Views.Grid.GridView
    Public Overridable Sub setSubTruoc_UpdateAll()
    End Sub
    Public Overridable Sub setSubTruoc_Luu()
    End Sub
    Public Overridable Sub setSubSau_Luu()
    End Sub
    Public Overridable Sub setSubTruoc_TaoMoi()
    End Sub
    Public Overridable Sub setSubSau_TaoMoi()
    End Sub
    Public Overridable Sub setSubTruoc_Sua()
    End Sub
    Public Overridable Sub setSubSau_Sua()
    End Sub
    Public Overridable Sub setSubTruoc_Xoa()
    End Sub
    Public Overridable Sub setSubSau_Xoa()
    End Sub
    Public Overridable Sub setSubTruoc_HuyThayDoi()
    End Sub
    Public Overridable Sub setSubSau_HuyThayDoi()
    End Sub
    Public Overridable Sub setSubTruoc_In()
    End Sub
    Public Overridable Sub setSubSau_In()
    End Sub
    Public Overridable Sub setSubTruoc_Thoat()
    End Sub
    Public Overridable Sub setSubTruoc_LamTuoi()
    End Sub
    Public Overridable Sub setSubSau_LamTuoi()
    End Sub
    Public Overridable Sub setSubTruoc_DauTien()
    End Sub
    Public Overridable Sub setSubSau_DauTien()
    End Sub
    Public Overridable Sub setSubTruoc_Truoc()
    End Sub
    Public Overridable Sub setSubSau_Truoc()
    End Sub
    Public Overridable Sub setSubTruoc_Sau()
    End Sub
    Public Overridable Sub setSubSau_Sau()
    End Sub
    Public Overridable Sub setSubTruoc_Cuoi()
    End Sub
    Public Overridable Sub setSubSau_Cuoi()
    End Sub
    '=====================================================
    Public Overridable Function setFuncTruoc_Luu() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_Luu() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_TaoMoi() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_TaoMoi() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_Sua() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_Sua() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_HuyThayDoi() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_Xoa() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_Xoa() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_HuyThayDoi() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_In() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_in() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_Thoat() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_LamTuoi() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_LamTuoi() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_DauTien() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_DauTien() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_Truoc() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_Truoc() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_Sau() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_Sau() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncTruoc_Cuoi() As Boolean
        Return True
    End Function
    Public Overridable Function setFuncSau_Cuoi() As Boolean
        Return True
    End Function
    '========= end các function khi xử lý ============
    ''' <summary>
    ''' set các đối tượng của form đơn
    ''' </summary>
    ''' <param name="ds">Tên DataSet</param>
    ''' <param name="dt">Tên Datatable</param>
    ''' <param name="bd">Tên BidingSource</param>
    ''' <param name="am">Tên TableAdapterManager</param>
    ''' <param name="ad">Tên TableAdapter</param>
    ''' <param name="controlfocus">Tên control bắt focus khi tạo mới</param>
    ''' <remarks></remarks>
    Public Sub setObj(ByVal ds As DataSet, ByVal dt As DataTable, ByVal bd As BindingSource, ByVal am As Object, ByVal ad As Object, ByVal controlfocus As BaseEdit)
        Me.bd = bd
        Me.ds = ds
        Me.dt = dt
        Me.am = am
        Me.ad = ad
        'Me.IGridView1 = igridview
        Me.controlFocus = controlfocus
        AddHandler controlfocus.Validating, AddressOf controlfocus_Validating
        iclass.setObj(ds, dt, bd, am, ad, Me.IGridView1, controlfocus)
    End Sub
    Private Function getKiemTraMaTonTai(ByVal sMa As String) As Boolean 'kiểm tra sự tồn tại của mã - dùng kiểm tra chung với igridview
        If Me.bd.Find("ma", sMa) = -1 Then 'nếu -1 nghĩa là ko tìm đc vị trí trong bindingsource
            Return False
        Else 'còn lại là tìm đc vị trí --> đã tồn tại
            Return True
        End If
    End Function
    Private Function getKiemTraMaTonTaiGrid(ByVal sMa As String) As Boolean 'kiểm tra sự tồn tại của mã - dùng kiểm tra chung với igridview
        Me.bd.EndEdit()
        Dim acc As Integer
        For index = 0 To Me.IGridView1.RowCount - 2
            If Me.IGridView1.GetRowCellValue(index, "ma").ToString.ToUpper = sMa.ToUpper Then
                acc = acc + 1
            End If
        Next
        If acc > 1 Then
            Return True
        End If
        Return False
    End Function
    Private Sub setReadonlyControl(ByVal b As Boolean)
        setReadonly(Me.LayoutControl1, b)
        If b Then
            Try
                Me.IGridView1.OptionsBehavior.Editable = False
                Me.IGridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None
            Catch ex As Exception
            End Try
        Else
            Try
                Me.IGridView1.OptionsBehavior.Editable = True
                Me.IGridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom
            Catch ex As Exception
            End Try
        End If
        If b Then
            Me.DxValidationProvider1.ValidationMode = DevExpress.XtraEditors.DXErrorProvider.ValidationMode.Manual
            setButtonTrangThaiSua(False)
        Else
            Me.DxValidationProvider1.ValidationMode = DevExpress.XtraEditors.DXErrorProvider.ValidationMode.Auto
            setButtonTrangThaiSua(True)
        End If
    End Sub
    Private Sub setButtonTrangThaiSua(ByVal b As Boolean) 'set nút lưu và xóa - khi ở trạng thái sửa thì mới cho phép thao tác trên nó (enable = true) - các trạng thái khác thì không cho (enable = false)
        Me.BarButtonGroupLuu.Enabled = b
        Me.BarButtonItemLuu.Enabled = b
        Me.BarStaticItemLuu.Enabled = b
        '==============================
        If m_Xoa Then
            Me.BarButtonItemXoa.Enabled = True
            Me.BarButtonGroupXoa.Enabled = True
            Me.BarStaticItemXoa.Enabled = True
        End If
        '===============================
        Me.BarButtonItemHuyThayDoi.Enabled = b
        Me.BarButtonGroupHuyThayDoi.Enabled = b
        Me.BarStaticItemHuyThayDoi.Enabled = b
        'Me.BarButtonItemLuu.Enabled = b
        'Me.BarButtonGroupLuu.Enabled = b
        'Me.BarStaticItemLuu.Enabled = b
        If b Then 'xử lý nút sửa (nếu nút lưu - xóa cho phép thì sửa ko cho phép và ngược lại)
            If m_TaoMoi Then
                Me.BarButtonItemTaoMoi.Enabled = False
                Me.BarButtonGroupTaoMoi.Enabled = False
                Me.BarStaticItemTaoMoi.Enabled = False
            End If
            Me.BarButtonItemSua.Enabled = False
            Me.BarButtonGroupSua.Enabled = False
            Me.BarStaticItemSua.Enabled = False
            Me.BarButtonItemFirst.Enabled = False
            Me.BarButtonItemPrevious.Enabled = False
            Me.BarButtonItemNext.Enabled = False
            Me.BarButtonItemLast.Enabled = False
            Me.BarButtonGroupDieuHuong.Enabled = False
            Me.BarButtonItemBaoCao.Enabled = False
            Me.BarButtonGroupBaoCao.Enabled = False
            Me.BarStaticItemBaoCao.Enabled = False
        Else
            If m_TaoMoi Then
                Me.BarButtonItemTaoMoi.Enabled = True
                Me.BarButtonGroupTaoMoi.Enabled = True
                Me.BarStaticItemTaoMoi.Enabled = True
            End If
            Me.BarButtonItemSua.Enabled = True
            Me.BarButtonGroupSua.Enabled = True
            Me.BarStaticItemSua.Enabled = True
            Me.BarButtonItemFirst.Enabled = True
            Me.BarButtonItemPrevious.Enabled = True
            Me.BarButtonItemNext.Enabled = True
            Me.BarButtonItemLast.Enabled = True
            Me.BarButtonGroupDieuHuong.Enabled = True
            Me.BarButtonItemBaoCao.Enabled = True
            Me.BarButtonGroupBaoCao.Enabled = True
            Me.BarStaticItemBaoCao.Enabled = True
        End If
        Me.RibbonControl.Refresh()
    End Sub
    ''' <summary>
    ''' set giá trị các cột ẩn trước khi lưu
    ''' </summary>
    ''' <param name="tên_cột">Tên cột</param>
    ''' <param name="giá_trị">Giá trị</param>
    ''' <remarks></remarks>
    Public Sub setSuaTruocKhiLuu(ByVal tên_cột As String, ByVal giá_trị As Object)
        If htEdit.ContainsKey(tên_cột) Then
            htEdit.Remove(tên_cột)
            htEdit.Add(tên_cột, giá_trị)
        Else
            Me.htEdit.Add(tên_cột, giá_trị)
        End If
    End Sub
    ''' <summary>
    ''' set giá trị mặc định cho cột không hiển thị trên form
    ''' </summary>
    ''' <param name="tên_cột">Tên cột</param>
    ''' <param name="giá_trị">Giá trị </param>
    ''' <remarks></remarks>
    Public Sub setMacDinhCotAn(ByVal tên_cột As String, ByVal giá_trị As Object)
        If htNew.ContainsKey(tên_cột) Then
            htNew.Remove(tên_cột)
            htNew.Add(tên_cột, giá_trị)
        Else
            Me.htNew.Add(tên_cột, giá_trị)
        End If
    End Sub
    ''' <summary>
    ''' set giá trị mặc định cho IGridView (Lưới danh sách)
    ''' </summary>
    ''' <param name="tên_cột">Tên trường cần gán</param>
    ''' <param name="giá_trị">Giá trị cần gán mặc định</param>
    ''' <remarks></remarks>
    Public Sub setMacDinhGrid(ByVal tên_cột As String, ByVal giá_trị As Object)
        ht.Add(tên_cột, giá_trị)
    End Sub
    Protected Overridable Sub BarButtonItemTaoMoi_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemTaoMoi.ItemClick, BarStaticItemTaoMoi.ItemClick
        Me.setSubTruoc_TaoMoi()
        If setFuncTruoc_TaoMoi() Then
            Me.setReadonlyControl(False)
            If Me.BarCheckItemNhapTuDanhSach.Checked Then
                Me.IGridView1.setFocusDongDauTien()
                Me.LayoutControlGroupThongTin.Expanded = False
                'xử lý set giá trị mặc định trên igridview1
                Me.setSubSau_TaoMoi()
                Me.state = 1
            Else
                Me.LayoutControlGroupThongTin.Expanded = True
                Me.controlFocus.Focus()
                Dim row As DataRowView = CType(Me.bd.AddNew(), DataRowView)
                'Me.IGridView1.Focus = False
                'Me.igrd()

                'set sau tạo mới
                Me.state = 1
                Me.setSubSau_TaoMoi()
                'xử lý set giá trị mặc định trên thông tin
                Dim Item As DictionaryEntry
                For Each Item In htNew
                    If dt.Columns.Contains(Item.Key.ToString) Then
                        row(Item.Key.ToString) = Item.Value
                    Else
                        DevExpress.XtraEditors.XtraMessageBox.Show("Cột '" & Item.Key.ToString & "' không tồn tại, bạn coi lại hàm 'setMacDinhCotAn' ?", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    End If
                Next
            End If

        End If
    End Sub
    Private Function getSave()
        Try
            bd.EndEdit()
            If Me.ds.HasChanges Then 'coi có thay đổi dữ liệu hay ko ?
                If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn 'Lưu' không ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                    setSubTruoc_UpdateAll()
                    am.updateAll(Me.ds)
                Else
                    ds.RejectChanges()
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return False
        End Try
        Return True
    End Function
    Protected Overridable Sub BarButtonItemLuu_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemLuu.ItemClick, BarStaticItemLuu.ItemClick
        Me.setSubTruoc_Luu()
        If Me.setFuncTruoc_Luu() Then
            IGridView1.setUpdateData()
            'sửa trước khi lưu
            Dim row As DataRowView = CType(Me.bd.Current(), DataRowView)
            Dim Item As DictionaryEntry
            For Each Item In htEdit
                If dt.Columns.Contains(Item.Key.ToString) Then
                    row(Item.Key.ToString) = Item.Value
                Else
                    DevExpress.XtraEditors.XtraMessageBox.Show("Cột '" & Item.Key.ToString & "' không tồn tại, bạn coi lại hàm 'setMacDinhCotAn' ?", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If
            Next
            'If iclass.getSave() And state <> 0 Then
            If state <> 0 Then
                If getSave() Then
                    setReadonlyControl(True)
                    Me.state = 0
                    Me.setSubSau_Luu()
                End If
            End If
        End If
    End Sub
    'kiểm tra trường hợp chưa có dữ liệu
    Private Function checkBindingSource() As Boolean
        Try
            If Me.bd.Count = 0 Then
                Return False
            Else
                Return True
            End If
        Catch ex As Exception
            DevExpress.XtraEditors.XtraMessageBox.Show("Chưa set đối tượng trong setObj(...) !!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Function
    Protected Overridable Sub BarButtonItemSua_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemSua.ItemClick, BarStaticItemSua.ItemClick
        Me.setSubTruoc_Sua()
        If checkBindingSource() Then
            If Me.setFuncTruoc_Sua() Then
                setReadonlyControl(False)
                state = 2
                Me.setSubSau_Sua()
            End If
        Else
            DevExpress.XtraEditors.XtraMessageBox.Show("Chưa có dữ liệu để 'Sửa'", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    Protected Overridable Sub BarButtonItemXoa_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemXoa.ItemClick, BarStaticItemXoa.ItemClick
        Me.setSubTruoc_Xoa()
        If Me.setFuncTruoc_Xoa Then
            If Me.iclass.getDelete() Then
                setReadonlyControl(True)
                Me.state = 0
                Me.setSubSau_Xoa()
            End If
        End If
    End Sub
    Public Function getRefresh()
        Try
            Me.bd.EndEdit()
            If Me.ds.HasChanges Then
                If DevExpress.XtraEditors.XtraMessageBox.Show("Dữ liệu đã có thay đổi, bạn có muốn hủy những thay đổi và làm tươi lại không ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                    Me.ds.RejectChanges()
                    Return True
                Else
                    Return False
                End If
            Else
                Dim position As Integer = Me.bd.Position
                Me.bd.Position = position
                If Not IsNothing(ad) Then
                    Me.ad.fill(Me.dt)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return False
            Exit Function
        End Try
        Return True
    End Function
    Protected Overridable Sub BarButtonItemLamTuoi_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemLamTuoi.ItemClick, BarStaticItemLamTuoi.ItemClick
        Me.setSubTruoc_LamTuoi()
        If Me.setFuncTruoc_LamTuoi Then
            If getRefresh() Then
                setReadonlyControl(True)
                Me.state = 0
                Me.setSubSau_LamTuoi()
            End If
        End If
    End Sub
    Public Function getState() As Integer
        Return state
    End Function
    Private Sub BarButtonItemBaoCao_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemBaoCao.ItemClick
        Me.setSubTruoc_In()
        If Me.getState <> 0 Then 'lưu trước khi in đảm bảo ko mất dữ liệu !
            If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn 'Lưu' trước khi in không ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                Me.BarButtonItemLuu.PerformClick()
            Else
                Me.BarButtonItemHuyThayDoi.PerformClick()
            End If
        End If
        If Me.setFuncTruoc_In() Then
            Me.setSubSau_In()
        End If
    End Sub
    Protected Overridable Sub BarButtonItemHuyThayDoi_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemHuyThayDoi.ItemClick, BarStaticItemHuyThayDoi.ItemClick
        Me.setSubTruoc_HuyThayDoi()
        setPostEditor(Me.LayoutControl1)
        If Me.setFuncTruoc_HuyThayDoi Then
            If Me.iclass.getUndo() Then
                setReadonlyControl(True)
                Me.state = 0
                Me.setSubSau_HuyThayDoi()
            End If
        End If
    End Sub
    Protected Overridable Sub BarButtonItemFirst_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemFirst.ItemClick
        Me.setSubTruoc_DauTien()
        If Me.setFuncTruoc_DauTien Then
            Me.iclass.getMoveFirst()
            Me.setSubSau_DauTien()
        End If
    End Sub
    Protected Overridable Sub BarButtonItemPrevious_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemPrevious.ItemClick
        Me.setSubTruoc_Truoc()
        If Me.setFuncTruoc_Truoc Then
            Me.iclass.getMovePrevious()
            Me.setSubSau_Truoc()
        End If
    End Sub
    Protected Overridable Sub BarButtonItemNext_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemNext.ItemClick
        Me.setSubTruoc_Sau()
        If Me.setFuncTruoc_Sau() Then
            Me.iclass.getMoveNext()
            Me.setSubSau_Sau()
        End If
    End Sub
    Protected Overridable Sub BarButtonItemLast_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemLast.ItemClick
        Me.setSubTruoc_Cuoi()
        If Me.setFuncTruoc_Cuoi Then
            Me.iclass.getMoveLast()
            Me.setSubSau_Cuoi()
        End If
    End Sub
    Protected Overridable Sub BarButtonItemThoat_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemThoat.ItemClick, BarStaticItemThoat.ItemClick
        Me.setSubTruoc_Thoat()
        If Me.setFuncTruoc_Thoat Then
            If Me.iclass.getSave() Then
                Me.Dispose()
                Me.Close()
            End If
        End If
    End Sub

    Protected Overridable Sub IFormDon_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn 'Thoát' khỏi màn hình '" & Me.Text & "' không ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
            Me.setSubTruoc_Thoat()
            If Me.setFuncTruoc_Thoat Then
                If Me.iclass.getSave() Then
                    Me.Dispose()
                    Me.Close()
                End If
            End If
        Else
            e.Cancel = True
        End If
    End Sub
    ''' <summary>
    ''' Set thông tin của doanh nghiệp 
    ''' </summary>
    ''' <param name="company">Tên công ty</param>
    ''' <param name="address">Địa chỉ</param>
    ''' <remarks></remarks>
    Public Sub setHeaderFooter(ByVal company As String, ByVal address As String)
        Me.IGridView1.setHeaderFooter(company, address, Me.printingSystem1, Me.PrintableComponentLink1)
    End Sub
    Public Sub setAppearanceSearchLookupEdit(ByVal ps As PersistentRepository)
        For Each item In ps.Items
            If TypeOf item Is RepositoryItemISearchLookUpEdit Then
                DirectCast(item, RepositoryItemISearchLookUpEdit).View.IndicatorWidth = 55
                DirectCast(item, RepositoryItemISearchLookUpEdit).View.OptionsView.EnableAppearanceEvenRow = True
                DirectCast(item, RepositoryItemISearchLookUpEdit).View.Appearance.EvenRow.BackColor = Color.LightCyan
                DirectCast(item, RepositoryItemISearchLookUpEdit).NullText = "[Chọn]"
                Me.view = CType(item, RepositoryItemISearchLookUpEdit).View
                AddHandler view.CustomDrawRowIndicator, AddressOf view_CustomDrawRowIndicator
            End If
        Next
    End Sub
    Public Sub setAppearanceSearchLookupEdit(ByVal lc As LayoutControl)
        For Each item In lc.Items
            If TypeOf item Is LayoutControlItem Then
                Dim ct As System.Windows.Forms.Control = DirectCast(item, LayoutControlItem).Control
                If TypeOf ct Is BaseEdit Then
                    If TypeOf ct Is ISearchLookupEdit Then
                        DirectCast(ct, ISearchLookupEdit).Properties.View.IndicatorWidth = 55
                        DirectCast(ct, ISearchLookupEdit).Properties.View.OptionsView.EnableAppearanceEvenRow = True
                        DirectCast(ct, ISearchLookupEdit).Properties.View.Appearance.EvenRow.BackColor = Color.LightCyan
                        DirectCast(ct, ISearchLookupEdit).Properties.NullText = "[Chọn]"
                        Me.view = CType(ct, SearchLookUpEdit).Properties.View
                        AddHandler view.CustomDrawRowIndicator, AddressOf view_CustomDrawRowIndicator
                    End If
                End If
            End If
        Next
    End Sub

    Private Sub setFilterConditionColumns()
        For index = 0 To Me.IGridView1.Columns.Count - 1
            Me.IGridView1.Columns(index).OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains
        Next
    End Sub
    'set lại @param cho adapter
    Protected Sub setParamAdapter()
        For index = 0 To Me.ad.Adapter.UpdateCommand.Parameters.Count
            If Me.ad.Adapter.UpdateCommand.Parameters.Item(index).ParameterName = "@uid" Or Me.ad.Adapter.UpdateCommand.Parameters.Item(index).ParameterName = "@ma" Then
            Else
                Me.ad.Adapter.UpdateCommand.Parameters.RemoveAt(index)
            End If
        Next
        For index = 0 To Me.ad.Adapter.DeleteCommand.Parameters.Count
            If Me.ad.Adapter.DeleteCommand.Parameters.Item(index).ParameterName = "@uid" Or Me.ad.Adapter.DeleteCommand.Parameters.Item(index).ParameterName = "@ma" Then
            Else
                Me.ad.Adapter.DeleteCommand.Parameters.RemoveAt(index)
            End If
        Next
    End Sub
    ''' <summary>
    ''' Phân quyền form đơn
    ''' </summary>
    ''' <param name="tạo_mới">quyền tạo mới</param>
    ''' <param name="sửa">quyền sửa</param>
    ''' <param name="xóa">quyền xóa</param>
    ''' <param name="dtThongTin">bảng dữ liệu phân quyền của phần thông tin</param>
    ''' <param name="dtDanhSach">bảng dữ liệu phân quyền của phần danh sách</param>
    ''' <remarks></remarks>
    Public Sub setPhanQuyen(ByVal tạo_mới As Boolean, ByVal sửa As Boolean, ByVal xóa As Boolean, ByVal dtThongTin As DataTable, ByVal dtDanhSach As DataTable)
        Me.m_TaoMoi = tạo_mới
        Me.m_Sua = sửa
        Me.m_Xoa = xóa
        Me.dtThongTin = dtThongTin
        Me.dtDanhSach = dtDanhSach
        If tạo_mới = False Then
            Me.BarButtonGroupTaoMoi.Enabled = False
            Me.BarButtonItemTaoMoi.Enabled = False
            Me.BarStaticItemTaoMoi.Enabled = False
        Else
            Me.BarButtonGroupTaoMoi.Enabled = True
            Me.BarButtonItemTaoMoi.Enabled = True
            Me.BarStaticItemTaoMoi.Enabled = True
        End If
        If sửa = False Then
            Me.BarButtonItemSua.Enabled = False
            Me.BarButtonGroupSua.Enabled = False
            Me.BarStaticItemSua.Enabled = False
        Else
            Me.BarButtonItemSua.Enabled = True
            Me.BarButtonGroupSua.Enabled = True
            Me.BarStaticItemSua.Enabled = True
        End If
        If xóa = False Then
            Me.BarButtonItemXoa.Enabled = False
            Me.BarButtonGroupXoa.Enabled = False
            Me.BarStaticItemXoa.Enabled = False
        Else
            Me.BarButtonItemXoa.Enabled = True
            Me.BarButtonGroupXoa.Enabled = True
            Me.BarStaticItemXoa.Enabled = True
        End If
        'set view thông tin field
        For index = 0 To Me.dtThongTin.Rows.Count - 1
            setPhanQuyenThongTin(dtThongTin.Rows(index).Item("control").ToString(), CBool(dtThongTin.Rows(index).Item("xem")))
        Next
        'set view danh sách cột igridviewchitiet01
        For index1 = 0 To Me.dtDanhSach.Rows.Count - 1
            setPhanQuyenDanhSach(dtDanhSach.Rows(index1).Item("control").ToString(), CBool(dtDanhSach.Rows(index1).Item("xem")))
        Next
        Me.RibbonControl.Refresh()
    End Sub
    Private Sub setPhanQuyenDanhSach(ByVal colName As String, ByVal view As Boolean)
        For index = 0 To Me.IGridView1.Columns.Count - 1
            If Me.IGridView1.Columns(index).Name.ToUpper = colName.ToUpper Then
                Me.IGridView1.Columns(index).Visible = view
            End If
        Next
    End Sub
    'kiểm tra các control trên thông tin để ẩn hiện - cho edit hay không ?
    'dtThongTin set biến toàn cục
    Private Sub setPhanQuyenThongTin(ByVal ItemName As String, ByVal view As Boolean)
        For Each item In LayoutControl1.Items
            If TypeOf item Is LayoutControlItem Then
                Dim ct As Windows.Forms.Control = DirectCast(item, LayoutControlItem).Control
                If ct IsNot Nothing Then
                    If ct.Name.ToUpper = ItemName.ToUpper Then
                        If view Then
                            CType(item, LayoutControlItem).Visibility = Utils.LayoutVisibility.Always
                        Else
                            CType(item, LayoutControlItem).Visibility = Utils.LayoutVisibility.Never
                        End If
                    End If
                End If
            End If
        Next
    End Sub
    Private Sub FormDon1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        setReadonlyTag(Me.LayoutControl1)
        setReadonlyControl(True)
        setAppearanceSearchLookupEdit(Me.PersistentRepository1)
        setAppearanceSearchLookupEdit(Me.LayoutControl1)
        setFilterConditionColumns()
        'set phân quyền

    End Sub
    
    Private Sub IGridView1_InitNewRow(sender As Object, e As DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs) Handles IGridView1.InitNewRow
        If Me.BarCheckItemNhapTuDanhSach.Checked Then 'check vô mới mặc định ở lưới
            Dim Item As DictionaryEntry
            For Each Item In ht
                If Me.IGridView1.Columns.Contains(Me.IGridView1.Columns(Item.Key.ToString)) Then
                    Me.IGridView1.SetFocusedRowCellValue(Item.Key.ToString, Item.Value)
                Else
                    DevExpress.XtraEditors.XtraMessageBox.Show("Cột '" & Item.Key.ToString & "' không tồn tại, bạn coi lại hàm 'setMacDinh' ?", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If
            Next
        End If
    End Sub
    Private Sub IGridView1_InvalidValueException(sender As Object, e As DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs) Handles IGridView1.InvalidValueException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.DisplayError
    End Sub

    Private Sub IGridView1_ValidatingEditor(sender As Object, e As DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs) Handles IGridView1.ValidatingEditor
        If Me.IGridView1.FocusedColumn.FieldName = "ma" And IGridView1.FocusedRowHandle <> -999997 Then
            Try
                If Me.getKiemTraMaTonTai(e.Value) And state = 1 Then
                    e.ErrorText = "'" & e.Value & "'đã tồn tại !"
                    e.Valid = False
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End If
    End Sub

    Public Sub New()
        InitializeComponent()
        ht = New Hashtable
        htNew = New Hashtable
        htEdit = New Hashtable
        lstGuiIdDeleted = New ArrayList
    End Sub

    Private Sub controlfocus_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs)
        Try
            If Me.getKiemTraMaTonTai(Me.controlFocus.EditValue) And state = 1 Then
                Me.controlFocus.ErrorText = "'" & controlFocus.EditValue & "'đã tồn tại !"
                e.Cancel = True
            End If
            If IsDBNull(Me.controlFocus.EditValue) Or IsNothing(Me.controlFocus.EditValue) Then
                Me.controlFocus.ErrorText = " không được rỗng !"
                e.Cancel = True
                Exit Sub
            ElseIf Me.controlFocus.EditValue.ToString.Trim = "" Then
                Me.controlFocus.ErrorText = " không được rỗng !"
                e.Cancel = True
                Exit Sub
            ElseIf Me.getKiemTraMaTonTaiGrid(Me.controlFocus.EditValue) And state = 2 Then
                Me.controlFocus.ErrorText = "'" & controlFocus.EditValue & "'đã tồn tại !"
                e.Cancel = True
                Exit Sub
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub InThôngTinToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)
        Me.IGridView1.ShowRibbonPrintPreview()
    End Sub

    Private Sub BarStaticItemBaoCao_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarStaticItemBaoCao.ItemClick
        Me.BarButtonItemBaoCao.PerformClick()
    End Sub

    Private Sub BarButtonGroupBaoCao_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonGroupBaoCao.ItemClick
        Me.BarButtonItemBaoCao.PerformClick()
    End Sub
End Class